/**
 * Created by LiH on 2018/7/19.
 */
import {request} from '../plugins/axios'
import wx from 'weixin-js-sdk'

function _verifyFailed({errMsg, message}) {
  Vue.$vux.toast.text(`微信接口认证失败:\n${errMsg || message}`, 'bottom');

  console.error(`WX_verifyFailed:\n${errMsg || message}`);
}

function _takeVerifyConf(HOST = '') {
  return request.get(`${HOST}/ApiService/weixin/signature`, {
    params: {
      url: window.location.href.split('#')[0]
    }
  });
}

function _config({APP_ID, timestamp, nonceStr, signature}) {
  wx.config({
    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
    appId: APP_ID, // 必填，公众号的唯一标识
    timestamp, // 必填，生成签名的时间戳
    nonceStr, // 必填，生成签名的随机串
    signature, // 必填，签名，见附录1
    jsApiList: [
      // 语音接口
      'startRecord', 'stopRecord', 'onVoiceRecordEnd', 'uploadVoice',
      'downloadVoice', 'playVoice', 'pauseVoice', 'onVoicePlayEnd',
      // 分享接口
      'onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ',
      'hideMenuItems', 'showMenuItems',
      // 图片接口
      'downloadImage', 'chooseImage', 'uploadImage', 'getLocalImgData',
    ],
    fail: _verifyFailed
  })
}

function _wxConfig(data) {
  if (typeof window.WeixinJSBridge !== 'undefined') {
    _config(data)
  } else {
    document.addEventListener('WeixinJSBridgeReady', function listener() {
      document.removeEventListener('WeixinJSBridgeReady', listener);
      _config(data)
    })
  }
}

function WX_verify(APP_ID, HOST) {
  if(typeof APP_ID !== 'undefined'){
    return _takeVerifyConf(HOST)
      .then(({data: {result: {data}}}) => {
        _wxConfig({
          APP_ID,
          ...data
        });
      })
      .catch(_verifyFailed)
  }
  return Promise.reject('WX_verify: APP_ID not exist')
}

function WX_hideAllMenuItem() {
  wx.hideMenuItems({
    menuList: [
      // 保护类
      /*'menuItem:copyUrl', */'menuItem:openWithQQBrowser', 'menuItem:openWithSafari', 'menuItem:share:email', 'menuItem:readMode',
      // 传播类
      'menuItem:share:appMessage', 'menuItem:share:timeline', 'menuItem:share:qq', 'menuItem:share:weiboApp', 'menuItem:favorite',
      'menuItem:share:facebook', 'menuItem:share:QZone'
    ]
  });
}

function WX_showMenuItemToShare() {
  wx.showMenuItems({
    menuList: ['menuItem:share:appMessage', 'menuItem:share:timeline', 'menuItem:favorite']
  });
}

/**
 * 分享config
 * @param config {link, title, desc, imgUrl}
 */
function WX_configShare(config) {
  wx.onMenuShareAppMessage(config);
  wx.onMenuShareTimeline(config);
}

export {WX_verify, WX_configShare, WX_hideAllMenuItem, WX_showMenuItemToShare}
